<?php

namespace app\admin\controller;

use app\common\controller\Adminbase;
use think\facade\Config;
use think\Request;

class Role extends Adminbase
{
    protected $auth_super;
    public function initialize()
    {
        parent::initialize();
        $this->auth_super = Config::get('mortalauth.auth_super') ?? '*ALL*';

    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $where[] = ['ro_type','=',1];
        $user_role = db('role')->find($this->this_user[config('mortalauth.auth_id')]);
        if($user_role['conditions'] != $this->auth_super){
            $where[] = ['id','=',$this->this_user[config('mortalauth.auth_id')]];
        }
        $info = db('role')->where($where)->order('id asc')->select();
        if($info){
            foreach ($info as $k=>$v){
                if($v['conditions'] == $this->auth_super){
                    $info[$k]['conditions'] = '超级权限';
                }
                if($v['id'] === $this->this_user[config('mortalauth.auth_id')]){
                    $info[$k]['no_delete'] = 1;
                }
            }
        }
        $filed = [
            ['field'=>'id','title'=>'ID'],
            ['field'=>'name','title'=>'角色名称'],
            ['field'=>'conditions','title'=>'角色权限'],
            ['field'=>'status','title'=>'角色状态'],
            ['field'=>'create_at','title'=>'添加时间'],
            ['field'=>'update_at','title'=>'更新时间'],
        ];
        $operate = $this->list_page;
        $operate['save'] = 'admin/role/create';
        $operate['edit'] = 'admin/role/edit';
        return view('public/list',['filed'=>$filed,'info'=>json_encode($info,JSON_UNESCAPED_UNICODE),'operate'=>$operate]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $operate['add'] = 'admin/role/save';
        $rule = db('menu')->field('id,pid,name')->select();
        foreach ($rule as $k=>$v){
            $rule[$k]['title'] = $v['name'];
            $rule[$k]['field'] = 'rule_id[]';
            unset($rule[$k]['name']);
        }
        $rule = array_recursion($rule);
        return view('role/save',['rule'=>json_encode($rule,JSON_UNESCAPED_UNICODE),'operate'=>$operate,'auth_super'=>$this->auth_super]);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = $request->post();
        if(!isset($data['name'])){
            return json(['code'=>1,'msg'=>'请设置角色名！']);
        }
        $conditions = $data['conditions']??'';
        if(!empty($conditions)&&$conditions!=$this->auth_super){
            return json(['code'=>1,'msg'=>'权限分配错误！']);
        }
        if(isset($data['rule_id'])&&!empty($data['rule_id'])&&empty($conditions)){
            $conditions = implode(',',$data['rule_id']);
        }
        $info = [
            'name' => $data['name'],
            'conditions' => $conditions,
            'status' => $data['status'],
            'ro_type' => 1
        ];
        $res = $this->add_info('role',$info);
        return json($res);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function edit(Request $request)
    {
        $id = $request->param('id');
        if(!$id){
            return json(['code'=>1,'msg'=>'数据错误，need ID']);
        }
        $data = db('role')->where('id',$id)->find();
        if(!$data){
            return json(['code'=>1,'msg'=>'数据不存在']);
        }
        $conditions = explode(',',$data['conditions']);
        $rule = db('menu')->field('id,pid,name')->select();
        foreach ($rule as $k=>$v){
            if($data['conditions'] == $this->auth_super){
                $rule[$k]['checked'] = true;
            }elseif (in_array($v['id'],$conditions)){
                $rule[$k]['checked'] = true;
            }
            $rule[$k]['title'] = $v['name'];
            $rule[$k]['field'] = 'rule_id[]';
            unset($rule[$k]['name']);
        }
        $rule = array_recursion($rule);
        return view('role/edit',['rule'=>json_encode($rule,JSON_UNESCAPED_UNICODE),'info'=>$data,'auth_super'=>$this->auth_super]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $data = $request->post();
        if(!isset($data['name'])){
            return json(['code'=>1,'msg'=>'请设置角色名！']);
        }
        $old = db('role')->where('id',$data['id'])->find();
        if(!$old){
            return json(['code'=>1,'msg'=>'数据不存在']);
        }
        $conditions = $data['conditions']??'';
        if(!empty($conditions)&&$conditions!=$this->auth_super){
            return json(['code'=>1,'msg'=>'权限分配错误！']);
        }
        if(isset($data['rule_id'])&&!empty($data['rule_id'])&&empty($conditions)){
            $conditions = implode(',',$data['rule_id']);
        }
        $info = [
            'id' => $data['id'],
            'name' => $data['name'],
            'conditions' => $conditions,
            'status' => $data['status'],
            'ro_type' => 1
        ];
        $res = $this->update_info('role',$info);
        return json($res);
    }

    /**
     * 删除指定资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function delete(Request $request)
    {
        $id = $request -> post('id');
        if(!is_array($id)){
            if(!is_numeric($id)){
                return json(['code'=>1,'msg'=>'数据错误']);
            }else{
                $id = explode(',',$id);
            }
        }
        if(is_array($id)){
            foreach($id as $val){
                $old = db('menu')->where('id',$val)->find();
                if(!$old){
                    return json(['code'=>1,'msg'=>'存在非数据库数据，请核查']);
                }
            }
            $res = db('role')->delete($id);
            if($res){
                return json(['code'=>200,'msg'=>'删除成功']);
            }else{
                return json(['code'=>1,'msg'=>'删除失败']);
            }
        }else{
            return json(['code'=>1,'msg'=>'数据错误']);
        }
    }
}
